<template>
    <ul class="tree-ul">
        <li class="tree-li">
            <span class="tree-expand" @click="handleExpand">
                <span v-if="data.children && data.children.length && !data.expand">+</span>
                <span v-if="data.children && data.children.length && data.expand">-</span>
            </span>
            <label>
                <input v-if="showCheckbox" v-model="data.checked" type="checkbox" @input="handleCheck" />
                <span>{{ data.title }}</span>
            </label>
            <template v-if="data.expand">
                <tree-node
                    v-for="(item, index) in data.children"
                    :key="index"
                    :data="item"
                    :show-checkbox="showCheckbox"
                ></tree-node>
            </template>
        </li>
    </ul>
</template>

<script type="text/javascript">
import { findComponentUpward } from '@/utils/assist';

export default {
    name: 'tree-node',
    components: {},
    data() {
        return {
            tree: findComponentUpward(this, 'tree')
        };
    },
    props: {
        data: {
            type: Object,
            default(){
                return {}
            }
        },
        showCheckbox: {
            type: Boolean,
            default: false,
        },
    },
    watch: {
        'data.children': {
            handler(data){
                if(data){
                    const checkedAll = !data.some(item => !item.checked);
                    this.$set(this.data, 'checked', checkedAll)
                }
            },
            deep: true
        }
    },
    methods: {
        handleExpand(){
            this.$set(this.data, 'expand', !this.data.expand)
            
            if(this.tree){
                this.tree.emitEvent('on-toggle-expand', this.data)
            }
        },
        handleCheck({target}){
            this.updateTreeDown(this.data, target.checked);
            console.log(this.tree)
            if(this.tree){
                this.tree.emitEvent('on-check-change', this.data)
            }
        },
        updateTreeDown(data, checked){
            this.$set(data, 'checked', checked);
            if(data.children && data.children.length){
                data.children.forEach(item => {
                    this.updateTreeDown(item, checked)
                })
            }
        }
    }
};
</script>

<style>
  .tree-ul, .tree-li{
    list-style: none;
    padding-left: 10px;
  }
  .tree-expand{
    cursor: pointer;
  }
</style>
